#include <iostream>
#include <thread>
#include <random>
#include <chrono>

std::mt19937 rng(std::random_device{}());
std::uniform_int_distribution<> dis(0, 100);

void sender(int packetId, std::atomic<bool>& receivedAck, std::atomic<bool>& stop) {
    while (!stop) {
        std::cout << "Sender: Sending packet " << packetId << std::endl;
        // 模拟丢包，10%概率丢包
        if (dis(rng) > 10) {
            receivedAck = true;
        } else {
            receivedAck = false;
        }
        std::this_thread::sleep_for(std::chrono::seconds(1));
        if (receivedAck) {
            std::cout << "Sender: Received ACK for packet " << packetId << std::endl;
            packetId++;
        } else {
            std::cout << "Sender: No ACK received, re - sending packet " << packetId << std::endl;
        }
    }
}

void receiver(std::atomic<bool>& receivedAck, std::atomic<bool>& stop) {
    while (!stop) {
        if (receivedAck) {
            std::cout << "Receiver: Received packet, sending ACK" << std::endl;
            receivedAck = false;
        }
        std::this_thread::sleep_for(std::chrono::seconds(1));
    }
}

int main() {
    std::atomic<bool> receivedAck(false);
    std::atomic<bool> stop(false);
    int packetId = 0;

    std::thread senderThread(sender, packetId, std::ref(receivedAck), std::ref(stop));
    std::thread receiverThread(receiver, std::ref(receivedAck), std::ref(stop));

    std::this_thread::sleep_for(std::chrono::seconds(5));
    stop = true;

    senderThread.join();
    receiverThread.join();

    return 0;
}